using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using EPiServer.Shell.Gadgets;

using EPiServer.Shell.Web;
using System.ComponentModel.Composition;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.Cms.Shell.UI.Models.RecentlyChangedPages;
using EPiServer.ChangeLog;
using EPiServer.Research.MobileCenter;
using EPiServer.BaseLibrary;
using System.Text;

using EPiServer.Research.MobileCenter.GadgetHelper;
using EPiServer.Research.MobileCenter.JSON;
using EPiServer.Research.MobileCenterGadgetLib;


namespace EPiServer.Research.MobileCenter.Example.Controllers
{
    /// <summary>
    /// Changed pages comparing pages recently changed and which properties have changed
    /// </summary>
    [Gadget(IconUrl="/modules/MobileCenterExampleGadgets/Content/Icon3.png", Name="MobileCenterChangedPages", Title="Changed Pages")]
    public class MobileCenterChangedPagesController : MobileCenterJsonBase
    {
        /// <summary>
        /// Gets the recently changed pages.
        /// </summary>
        /// <returns></returns>
        public List<PageVersion> GetRecentlyChangedPages()
        {
            IChangeLog ChangeLog = (IChangeLog)ClassFactory.CreateInstance(typeof(IChangeLog), new object[0]);

            List<PageVersion> pfs = new List<PageVersion>();

            ChangeLogQueryInfo info = new ChangeLogQueryInfo
            {
                Category = 1,
                MaxRecordsToReturn = 30
            };

            IList<IChangeLogItem> changedPages = null;


            changedPages = ChangeLog.GetChanges(info, ReadDirection.Forwards, SortOrder.Descending);
            if (changedPages == null)
            {
                return null;
            }

            foreach (IChangeLogItem item in changedPages)
            {
                ChangeLogPage.ActionType type = (ChangeLogPage.ActionType)item.Action;
                if (((type == ChangeLogPage.ActionType.Create) || (type == ChangeLogPage.ActionType.Publish)) || ((type == ChangeLogPage.ActionType.Save)))
                {
                    PageVersion pageVer = PageVersion.Load(((ChangeLogPage)item).PageReference);
                    if (pageVer != null)
                    {
                        int tmpcount = pfs.Where(v => v.ID.ID == pageVer.ID.ID).ToList().Where(pv => pv.LanguageBranch == pageVer.LanguageBranch).ToList().Count;
                        if (tmpcount == 0)
                        {
                            pfs.Add(pageVer);
                        }
                    }
                }
            }

            return pfs;
        }

        /// <summary>
        /// Gets the changed pages.
        /// </summary>
        /// <returns></returns>
        public List<MobileCenterPageChanged> GetChangedPages()
        {
            List<MobileCenterPageChanged> MobileCenterchanged = new List<MobileCenterPageChanged>();

            foreach (var item in GetRecentlyChangedPages())
            {
                var list = PageVersion.List(item.ID, item.LanguageBranch);
                if (list.Count > 1)
                {
                    var newval = new MobileCenterPageChanged();
                    newval.pageid = list[list.Count-1].ID.ID;

                    newval.version = PropertyDiff.GetPropertyChanges(list[list.Count-1], list[list.Count-2]);
                    MobileCenterchanged.Add(newval);
                }
            }

            if (MobileCenterchanged.Count == 0)
            {
                MobileCenterPageChanged ipc = new MobileCenterPageChanged();
                ipc.pageid = PageReference.StartPage.ID;
                ipc.version = new EPiServer.Research.MobileCenterGadgetLib.Version(PageReference.StartPage.WorkID, String.Empty, DateTime.Now, "Published");
                MobileCenterchanged.Add(ipc);
            }

            return MobileCenterchanged;

        }

        public List<MobileCenterPageChanged> ChangedPagesList { get; set; }

        /// <summary>
        /// Gets the page view
        /// </summary>
        /// <param name="pageid">The pageid.</param>
        /// <returns></returns>
        public ActionResult GetPage(int pageid)
        {
            //shouldnt do this all the time but only once and then have it in memory
            List<MobileCenterPageChanged> changedpages = ChangedPagesList ?? GetChangedPages();

            var page = new MobileCenterPageChanged();
            foreach (var item in changedpages)
            {
                if (item.pageid == pageid)
                {
                    page = item;
                    break;
                }
            }
            return View(page);
        }

        /// <summary>
        /// Shows the index view list of changed pages
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            //shouldnt do this all the time but only once and then have it in memory
            List<MobileCenterPageChanged> changedpages = ChangedPagesList ?? GetChangedPages();

            var page = new MobileCenterPageChanged();
            if (changedpages.Count > 0)
            {
                return View(changedpages[0]);
            }
            page.pageid = PageReference.StartPage.ID;
            return View(page);
           
        }

        /// <summary>
        /// Gets the list view of changed pages
        /// </summary>
        /// <returns></returns>
        public override List<CellView> GetListView()
        {
            List<MobileCenterPageChanged> changedpages = ChangedPagesList ?? GetChangedPages();

            List<CellView> gadgets = new List<CellView>();

            foreach (var item in changedpages)
            {
                PageData pd = DataFactory.Instance.GetPage(new PageReference(item.pageid));
                
                CellView c = new CellView();
                c.Name = pd.PageName + " " + pd.Changed.ToShortDateString()+" " +pd.Changed.ToShortTimeString();

                WebView w = new WebView();
                w.UseDefaultUrl = false;
                w.CustomUrl = GetUrlForView(pd.PageLink.ID.ToString());
                w.Name = pd.PageName;

                c.WebViewToPush = w;
                gadgets.Add(c);
            }

            return gadgets;
        }


        /// <summary>
        /// Gets the URL for view.
        /// </summary>
        /// <param name="pageid">The pageid.</param>
        /// <returns></returns>
        public string GetUrlForView(string pageid)
        {
            return "recently/" + pageid;
        }

        /// <summary>
        /// Gets the web view.
        /// </summary>
        /// <returns></returns>
        public override WebView GetWebView()
        {
            throw new NotImplementedException();
        }

        public override bool ShouldReturnList
        {
            get
            {
                return true;
            }
           
        }

    }
}
